package com.atguigu.encryption.utils;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;

@Slf4j
public class SM4Util {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public static String encryptSM4(byte[] data,byte[] key) {
        log.info("key数组的长度为：{}",key.length);
        if (key.length != 16) {
            throw new RuntimeException("加密失败，SM4密钥长度应为16字节");
        }
        try {
            Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding", "BC");
            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "SM4");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encryptedBytes = cipher.doFinal(data);
            return Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    public static String decryptSM4(byte[] data,byte[] key) {
//        if (key.length != 16) {
//            throw new RuntimeException("解密失败，SM4密钥长度应为16字节");
//        }
//        try {
//            Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding", "BC");
//            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "SM4");
//            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
//            byte[] decryptedBytes = cipher.doFinal(data);
//            return Base64.getEncoder().encodeToString(decryptedBytes);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
public static String decryptSM4(byte[] data, byte[] key) {
        log.info("密钥长度："+key.length);
    if (key.length != 16) {
        throw new RuntimeException("解密失败，SM4密钥长度应为16字节");
    }
    try {
        Cipher cipher = Cipher.getInstance("SM4/ECB/PKCS5Padding", "BC");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "SM4");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(data));
        return new String(decryptedBytes);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}


    public static void main(String[] args) {
        byte[] key = "1234567812345678".getBytes(); // 16字节密钥
        byte[] data = "Hello, SM4!".getBytes();

        // 加密
        String encryptedBase64 = encryptSM4(key, data);
        System.out.println("Encrypted (Base64): " + encryptedBase64);

        // 解密
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedBase64);
        String decryptedBase64 = decryptSM4(key, encryptedBytes);
        System.out.println("Decrypted (Base64): " + decryptedBase64);
    }
}
